﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MBG.Extensions.Core;

namespace MathLib
{
    public static class General
    {
        public static int GreatestCommonFactor(int n1, int n2)
        {
            IEnumerable<int> commonFactors = CommonFactors(n1, n2);

            if (commonFactors.Count() > 0)
            {
                return commonFactors.Max();
            }
            else { return -1; }
        }
        public static IEnumerable<int> CommonFactors(int n1, int n2)
        {
            IEnumerable<int> n1Factors = Factors(n1);
            IEnumerable<int> n2Factors = Factors(n2);

            return (from x in n1Factors
                    where x.In(n2Factors)
                    select x);
        }
        public static IEnumerable<int> Factors(int n)
        {
            List<int> factors = new List<int>();

            for (int i = 2; i <= n; i++)
            {
                if (n.IsMultipleOf(i))
                {
                    factors.Add(i);
                }
            }

            return factors;
        }
        public static IEnumerable<int> PrimeFactors(int n)
        {
            List<int> factors = new List<int>();
            int temp = n;

            while (temp != 1)
            {
                for (int i = 2; i <= temp; i++)
                {
                    if (temp.IsMultipleOf(i))
                    {
                        factors.Add(i);
                        temp = temp / i;
                        break;
                    }
                }
            }

            return factors;
        }
    }
}